package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    //通过dubbo网络远程调用服务
    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUsername(username);
        if(user == null){
            return null;
        }
        //创建集合
        List<GrantedAuthority> list = new ArrayList<>();

        //如果用户不为空,进行授予角色
        Set<Role> roles = user.getRoles();
      if(roles!=null && roles.size()>0){
          for (Role role : roles) {
              list.add(new SimpleGrantedAuthority(role.getKeyword()));
              //授予权限
              Set<Permission> permissions = role.getPermissions();
              if(permissions!=null && permissions.size()>0){
                  for (Permission permission : permissions) {
                      list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                  }
              }
          }
      }

      //调用security的user对象进行真正的验证与授权操作
        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);

    }
}
